package com.sport.apis.aop;

import com.sport.model.user.bos.AccountUserBo;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Aspect
@Component
public class DIAccountBoAop {

    @Pointcut(value = "@annotation(com.sport.apis.annotation.DIAccountUserBo)")
    public void checkDIAccountBo() {}

    @Around("checkDIAccountBo()")
    public Object initOperation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        Object[] methodArgs = proceedingJoinPoint.getArgs();

        for (int i = 0; i < methodArgs.length; ++i) {
            Class<?> clazz = methodArgs[i].getClass();
            String parameterClassToString = clazz.toString();
            if (parameterClassToString.endsWith("Dto")) {
                methodArgs[i] = parameterSetIntoParameter(methodArgs[i]);
                break;
            } else if (clazz.equals(ArrayList.class)) {
                ArrayList methodArg = (ArrayList) methodArgs[i];
                ArrayList copyArg = new ArrayList();
                for (int single = 0; single < methodArg.size(); ++single)
                    copyArg.add(parameterSetIntoParameter(methodArg.get(single)));

                methodArgs[i] = copyArg;
            }
        }

        return proceedingJoinPoint.proceed(methodArgs);
    }

    private Object parameterSetIntoParameter(Object target) {
        try {
            Class targetClass = target.getClass();
            Method setAccountUserBo = targetClass.getDeclaredMethod("setAccountUserBo", AccountUserBo.class);
            setAccountUserBo.invoke(target, AccountUserBo.getUser());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return target;
    }
}
